<?php

namespace App\Models\Admin;

// use Illuminate\Contracts\Auth\MustVerifyEmail;

use App\Traits\DateFormatTrait;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;

class SysUser extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable;

    protected $hidden = ['password', 'deleted_at', 'created_at', 'updated_at', 'status', 'sysRoles'];

    protected $fillable = [
        'username', 'password', 'gender', 'nickname', 'name', 'email', 'mobile', 'status', 'avatar',
    ];

    protected $casts = [
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d'
    ];

    protected $appends = ['perms'];


    public function sysRoles() {
        return $this->belongsToMany(
            SysRole::class,
            SysUserRole::class
        )->select('code', 'id')->with(['permissions', 'menus' => function($query) {
            $query->with('children');
        }]);
    }

    public function getPermsAttribute()
    {
        return $this->sysRoles->map(function($role) {
            return $role->permissions->pluck('perm')->toArray();
        })->collapse()->toArray();
    }

    public function scopeList($query)
    {
        $this->makeHidden(['perms']);
        return $query->select('*');
    }


    // public function permissions()
    // {
    //     // 使用 hasManyThrough 定义 User 与 Permission 之间的关联关系
    //     return $this->hasManyThrough(SysPermission::class, SysRole::class, 'sys_role_id', 'sys_user_id', 'id', 'id');
    // }
}
